#!/usr/bin/python3
# -*- coding:utf-8 -*-
# __author__ = '__Tony__'
import os
import sys
import time
import uvicorn
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import ORJSONResponse
from config.config import CFG
from log import log, Loggers
from errors import global_exception_handlers
# # 设置环境类型, 用环境变量更灵活
# CFG.env = sys.argv[1] if sys.argv[0] and sys.argv[1] in ['dev',  'test', 'prod'] else 'dev'
from app.yg_crm.routes import yg_crm_app
from app.yg_crm.routes import test_router
from app.oss_api import oss_api
from tutorial import app03
from fastapi_offline import FastAPIOffline
from database import init_db
# from middleware.LogMiddleware import RequestContextLogMiddleware
# from fastapi.exceptions import RequestValidationError
# from fastapi.responses import PlainTextResponse
# from starlette.exceptions import HTTPException as StarletteHTTPException


app = FastAPIOffline(
    title='YG-CRM API Docs',
    description='YG-CRM API Docs API接口文档',
    version='1.0.0',
    docs_url='/docs',
    redoc_url='/redocs',
    default_response_class=ORJSONResponse,
    exception_handlers=global_exception_handlers
)

init_db(app)
# mount表示将某个目录下一个完全独立的应用挂载过来，这个不会在API交互文档中显示
# app.mount(path='/static', app=StaticFiles(directory='./coronavirus/static'), name='static')  # .mount()不要在分路由APIRouter().mount()调用，模板会报错


@app.middleware('http')
async def add_process_time_header(request: Request, call_next):  # call_next将接收request请求做为参数
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers['X-Process-Time'] = str(process_time)  # 添加自定义的以“X-”开头的请求头
    return response


app.add_middleware(
    CORSMiddleware,
    allow_origins=CFG().cfg.allow_origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)



app.include_router(app03, prefix='/chapter03', tags=['第三章 请求参数和验证'])
# app.include_router(app04, prefix='/chapter04', tags=['第四章 响应处理和FastAPI配置'])
# app.include_router(app05, prefix='/chapter05', tags=['第五章 FastAPI的依赖注入系统'])
# app.include_router(app06, prefix='/chapter06', tags=['第六章 安全、认证和授权'])
# app.include_router(app07, prefix='/chapter07', tags=['第七章 FastAPI的数据库操作和多应用的目录结构设计'])
# app.include_router(app08, prefix='/chapter08', tags=['第八章 中间件、CORS、后台任务、测试用例'])
app.include_router(yg_crm_app, prefix='/fastapi', tags=['yg_crm_app'])
app.include_router(oss_api, prefix='/oss', tags=['yg_crm_oss'])
app.include_router(test_router, prefix='/test', tags=['测试专用'])


if __name__ == '__main__':
    # uvicorn.run('run:app', host='0.0.0.0', port=8000, reload=True, workers=1, env_file="config/dev.ini")
    if os.getenv("Mode") == "dev":
        os.system("fastapi dev run.py")
    else:
        config = uvicorn.Config('run:app', host='0.0.0.0', port=8000, workers=os.cpu_count(), limit_max_requests=1024 * 1024 * 1024)
        server = uvicorn.Server(config)
        # 将uvicorn输出的全部让loguru管理
        Loggers.init_config()
        server.run()


